	//    This file is part of Open WordSearch.
//
//    Open WordSearch is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    Open WordSearch is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with Open WordSearch.  If not, see <http://www.gnu.org/licenses/>.
//
//        Copyright 2009, 2010 Brendan Dahl <dahl.brendan@brendandahl.com>
//              http://www.brendandahl.com
package com.abhipedro.wordsearch.view;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.TextView;

import com.abhipedro.wordsearch.util.Constants;
import com.abhipedro.wordsearch.util.TopExceptionHandler;
import com.abhipedro.wordsearch.view.runnables.OnlineHighScore;

public class MenuActivity extends Activity implements OnClickListener {

	/** The Font */
	private Typeface m_typeface;

	/** The Animations .*/
	private Animation mButtonFlickerAnimation;
	private Animation mFadeOutAnimation;
	private Animation mAlternateFadeOutAnimation;
	
	/** The Buttons .*/
	private TextView optionsButoon;
	private TextView newButton;
	private TextView highscoreButton;
	private TextView aboutButton;
	private TextView exitButton;
	
    boolean hasCrashReport = false;
    
    public  String PREFS_NAME;
	private SharedPreferences m_settings ;
	public static String RATED_APP_USE_COUNT_KEY = "times_used_";
	
	public static String PREFS_FILE_NAME = "MyPrefsFile";
	public static String RATED_PREF_KEY = "_rated";
	public static String MARKET_RATE_URL = "market://details?id=com.abhipedro.wordsearch.view";
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_menu);
		
		Thread.setDefaultUncaughtExceptionHandler(new TopExceptionHandler(this));
		
		PREFS_NAME = PREFS_FILE_NAME;
		m_settings = getSharedPreferences(PREFS_NAME, 0);

		m_typeface = Typeface.createFromAsset(getAssets(), Constants.MENU_FONT);
		mButtonFlickerAnimation = AnimationUtils.loadAnimation(this, R.anim.button_flicker);
	    mFadeOutAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_out);
	    mAlternateFadeOutAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_out);
		
		// Set up click listeners for all the buttons
		optionsButoon = (TextView) findViewById(R.id.continue_button);
		optionsButoon.setOnClickListener(this);
		optionsButoon.setTypeface(m_typeface);
		newButton = (TextView) findViewById(R.id.new_button);
		newButton.setTypeface(m_typeface);
		newButton.setOnClickListener(this);
		highscoreButton = (TextView) findViewById(R.id.highscores_button);
		highscoreButton.setTypeface(m_typeface);
		highscoreButton.setOnClickListener(this);
		aboutButton = (TextView) findViewById(R.id.about_button);
		aboutButton.setTypeface(m_typeface);
		aboutButton.setOnClickListener(this);
		exitButton = (TextView) findViewById(R.id.exit_button);
		exitButton.setTypeface(m_typeface);
		exitButton.setOnClickListener(this);

		
		reportCrash();
	}

	@Override
	protected void onResume() {
		super.onResume();
		TextView title = (TextView) findViewById(R.id.title);
		title.setTypeface(m_typeface);
		Music.play(this, R.raw.main);
		
		slideAnimation(  newButton);
		slideAnimation( optionsButoon );
		slideAnimation( highscoreButton);
		slideAnimation( aboutButton);
		slideAnimation( exitButton) ;
		
		showratedialog();
	}
	
	private void slideAnimation(TextView v) {
		if (null != v) {
			if(v.getVisibility()==View.INVISIBLE)
			v.setVisibility(View.VISIBLE);
			v.clearAnimation();
			Animation anim = AnimationUtils.loadAnimation(this,R.anim.button_slide);
			anim.setStartOffset(200L);
			v.startAnimation(anim);
		}
	}

	@Override
	protected void onPause() {
		Music.stop(this);
		super.onPause();
	}
	
	@Override
	protected void onDestroy() {
		Music.stop(this);
		super.onDestroy();
	}

	public void onClick(View v) {
		Intent i;
		switch (v.getId()) {
		case R.id.new_button:
			final Intent    i4 = new Intent(this, WordSearchActivity.class);
			AlertDialog.Builder alert = new AlertDialog.Builder(this);
			alert.setTitle("Enter your name");
			final EditText input = new EditText(this);
			SharedPreferences _settings = getSharedPreferences(	Constants.PREFS_NAME, 0);
			String name = _settings.getString(Constants.PREFS_PLAYER_NAME, "");
			input.setText(name);

			alert.setView(input);

			alert.setPositiveButton("Ok",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,	int whichButton) {
							String value = input.getText().toString();

							SharedPreferences _settings = getSharedPreferences(	Constants.PREFS_NAME, 0);

							SharedPreferences.Editor editor = _settings.edit();
							editor.putString(Constants.PREFS_PLAYER_NAME,
											value);
							editor.commit();

							mButtonFlickerAnimation.setAnimationListener(new StartActivityAfterAnimation(
											i4));
							newButton.startAnimation(mButtonFlickerAnimation);

						}
					});

			alert.setNegativeButton("Cancel",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							dialog.cancel();
						}
					});

			alert.show();
			
			break;
			
		case R.id.continue_button:
			i = new Intent(this, SettingsActivity.class);
			mButtonFlickerAnimation.setAnimationListener(new StartActivityAfterAnimation(i));
			optionsButoon.startAnimation(mButtonFlickerAnimation);
			break;

		case R.id.about_button:
			String url  = "";
			String pedroApps ="market://details?id=com.pedronveloso.trivialdroid";
			String myApps ="market://search?q=pub:\"Abhishek Kumar\"";
			int val = new Random().nextInt(2);
			url = val == 0 ? pedroApps : myApps;
			
			i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
		    mButtonFlickerAnimation.setAnimationListener(new StartActivityAfterAnimation(i));
		    aboutButton.startAnimation(mButtonFlickerAnimation);
			break;
			
		case R.id.highscores_button:
			Intent i2;
			i2 = new Intent(this, OnlineHighScore.class);
			 mButtonFlickerAnimation.setAnimationListener(new StartActivityAfterAnimation(i2));
			 highscoreButton.startAnimation(mButtonFlickerAnimation);
			break;

		case R.id.exit_button:
			// Confirm quiting dialog
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Exit?").setCancelable(false).setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,	int id) {
									MenuActivity.this.finish();
								}
							}).setNegativeButton("Cancel",	new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,	int id) {
									dialog.cancel();
								}
							}).setNeutralButton("Rate App", new DialogInterface.OnClickListener() {
						    	  public void onClick(DialogInterface dialog, int whichButton) {
						    		  Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(MARKET_RATE_URL));
									startActivity(marketIntent);
										
						    	  }
						    	});
			final AlertDialog confirmExitDialog = builder.create();
			confirmExitDialog.show();
			break;
		}
	}


	protected class StartActivityAfterAnimation implements
			Animation.AnimationListener {
		private Intent mIntent;

		StartActivityAfterAnimation(Intent intent) {
			mIntent = intent;
		}

		public void onAnimationEnd(Animation animation) {
			startActivity(mIntent);
		}

		public void onAnimationRepeat(Animation animation) {
		}

		public void onAnimationStart(Animation animation) {
		}

	}
	
//    @Override
//	public boolean onKeyDown(int keyCode, KeyEvent event) {
//	    if ((keyCode == KeyEvent.KEYCODE_BACK) ) {
//			boolean rated = m_settings.getBoolean(RATED_PREF_KEY, false);
//	    	
//	    	AlertDialog.Builder alert = new AlertDialog.Builder(MenuActivity.this);
//	    	alert.setTitle("Rate App.");
//	    	alert.setMessage("Would you like rate Word Search in Android market?");
//	    	alert.setPositiveButton("Rate", new DialogInterface.OnClickListener() {
//	    	public void onClick(DialogInterface dialog, int whichButton) {
//	    		  SharedPreferences.Editor editor = m_settings.edit();
//	    		  editor.putBoolean(RATED_PREF_KEY, true);
//	    		  editor.commit();
//	    		  Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(MARKET_RATE_URL));
//	    		  startActivity(marketIntent);
//	    	  }
//	    	});
//	    	alert.setNegativeButton("Later", new DialogInterface.OnClickListener() {
//	    	  public void onClick(DialogInterface dialog, int whichButton) {
//	    		  MenuActivity.this.finish();
//	    	  }
//	    	});
//
//	    	if(!rated) {
//	    		alert.show();
//	    		return true;
//	    	}
//	    	
//	    }
//	    return super.onKeyDown(keyCode, event);
//	}
//    

	private void showratedialog() {

		boolean rated = m_settings.getBoolean(RATED_PREF_KEY, false);
		AlertDialog.Builder alert = new AlertDialog.Builder(MenuActivity.this);
		alert.setTitle("Rate App.");
		alert.setMessage("Please consider rating Word Search in Android market :)");
		alert.setPositiveButton("Rate", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				SharedPreferences.Editor editor = m_settings.edit();
				editor.putBoolean(RATED_PREF_KEY, true);
				editor.commit();
				Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri
						.parse(MARKET_RATE_URL));
				startActivity(marketIntent);
			}
		});
		alert.setNegativeButton("Later", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				dialog.cancel();
			}
		});

		if (!rated) {
			SharedPreferences.Editor editor = m_settings.edit();
			int useCount = m_settings.getInt(RATED_APP_USE_COUNT_KEY, 0);
			editor.putInt(RATED_APP_USE_COUNT_KEY, useCount + 1);
			editor.commit();
			if (useCount == 3) {
				editor.putInt(RATED_APP_USE_COUNT_KEY, 0);
				editor.commit();
				alert.show();
			}
		}
	}
	
	
private	String mTrace ;
	
	private void reportCrash() {
		String line;
		String trace = "";

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					MenuActivity.this.openFileInput("stack.trace")));
			while ((line = reader.readLine()) != null) {
				trace += line + "\n";
			}

			hasCrashReport = true;
		} catch (FileNotFoundException fnfe) {
		} catch (IOException ioe) {
		}

		mTrace = trace;
		
		if (hasCrashReport) {
			
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Send Crash Report");
			builder.setMessage("Please send the crash report, so we can improve future versions of Word Search , Thanks.")
			       .setCancelable(false)
			       .setPositiveButton("Send", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			           Intent sendIntent = new Intent(Intent.ACTION_SEND);
			   			String subject = "Word Search Crash Report";
			   			String body = "Mail  " + "\n\n" + mTrace + "\n\n";

			   			sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {"mobilenewsdev@gmail.com" });
			   			sendIntent.putExtra(Intent.EXTRA_TEXT, body);
			   			sendIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
			   			sendIntent.setType("message/rfc822");

			   			MenuActivity.this.startActivity(Intent.createChooser(sendIntent,"Title: Word Search Crash Report"));
			   			MenuActivity.this.deleteFile("stack.trace");

			           }
			       })
			       .setNegativeButton("Ignore", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			                dialog.cancel();
			           }
			       });
			AlertDialog alert = builder.create();
			alert.show();
		}
	}


}